﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DALEntities;
using MapEntities;
using Microsoft.SharePoint.Client;
using System.Collections;
using ServerPlatform.DataProvider.Providers.SharePointLibrary;
using System.Web;
using System.Data;

namespace ServerPlatform.DataProvider.Providers
{
    public class SharepointDataProvider : BaseDataProvider
    {
        public override List<DALEntities.ViewSchema> GetViews()
        {
            throw new NotImplementedException();
        }

        public override void Connect(string connectionString)
        {
            throw new NotImplementedException();
        }

        private DataTable GetAsDataTable(List list, ListItemCollection col)
        {
            DataTable res = new DataTable();
            
            foreach (ListItem item in col)
            {
                ArrayList valueList = new ArrayList();
                for (int i = 0; i< list.Fields.Count;i++) {
                    object val = item.FieldValues[list.Fields[i].InternalName]; 
                    if (res.Columns.IndexOf(list.Fields[i].Title) < 0)
                    {
                        DataColumn column = new DataColumn(list.Fields[i].Title);                       
                        column.DataType = val == null ? Type.Missing.GetType(): val.GetType();
                        res.Columns.Add(column);                       
                    } 
                   
                    valueList.Add(val);
                }

                DataRow row = res.NewRow();
                row.ItemArray = valueList.ToArray();
                res.Rows.Add(row);
                
            }
            return res;
        }

        public override DALEntities.ViewResult GetViewResult(DALEntities.ViewRequest request)
        {
            if (string.IsNullOrEmpty(request.ConnectionString.Trim()))
            {
                request.ConnectionString = Microsoft.SharePoint.SPContext.Current.Site.Url.ToString();
            }
            ClientContext clientCtx = new ClientContext(request.ConnectionString);
            string vname = request.ViewName;
            Microsoft.SharePoint.Client.Web myweb = clientCtx.Web;
            clientCtx.Load(myweb);
            clientCtx.Load(myweb, lists => lists.Lists.Where(list => list.Title == vname));
            clientCtx.ExecuteQuery();
            List mylist = myweb.Lists[0];
            clientCtx.Load(mylist.Fields);
            clientCtx.Load(mylist, p => p.Fields.Where(p2 => p2.Hidden == false && p2.FromBaseType == false));
            clientCtx.ExecuteQuery();
            string fields = "<View><ViewFields>";
            foreach (Microsoft.SharePoint.Client.Field itemfield in mylist.Fields)
            {
                fields += "<FieldRef Name='" + itemfield.InternalName + "' />";
            }
            fields += "</ViewFields></View>";           
            CamlQuery query = new CamlQuery();
            query.ViewXml = fields;
            ListItemCollection data = mylist.GetItems(query);
            
            clientCtx.Load(data);
            clientCtx.ExecuteQuery();
            //SPList datalist = new SPList();
            //foreach (ListItem item in data)
            //{
            //    SPItem myitem = new SPItem();
            //    foreach (KeyValuePair<string, object> pair in item.FieldValues)
            //    {
            //        SPColumn mycol = new SPColumn(pair.Key, pair.Value);
            //        myitem.Add(mycol);
            //    }
            //    datalist.Add(myitem);
            //}
            DataTable table = GetAsDataTable(mylist, data);
            clientCtx.Dispose();

            DataView view = table.DefaultView;
            if (request.ExtraData != null && !string.IsNullOrEmpty(request.ExtraData.ToString()))
            {
                view = new DataView(table, request.ExtraData.ToString(), "", DataViewRowState.CurrentRows);
            }

            return new DALEntities.ViewResult() { RequestID = request.ID, Data = (IList)view };
        }

        public override DALEntities.ProviderSource Source
        {
            get { return ProviderSource.SP; }
        }

        private DataType GetDataType(FieldType itemtype)
        {
            switch (itemtype)
            {
                case FieldType.Currency:
                    return DataType.Decimal;
                case FieldType.DateTime:
                    return DataType.DateTime;
                case FieldType.Integer:
                    return DataType.Integer;
                case FieldType.Number:
                    return DataType.Double;
                case FieldType.Text:
                    return DataType.String;
                default:
                    return DataType.Unknown;
            }

        }
        public override DALEntities.ViewSchemaList GetSchema(DALEntities.SchemaRequest request)
        {
            DALEntities.ViewSchemaList xresult = new DALEntities.ViewSchemaList();
            if (string.IsNullOrEmpty(request.ConnectionString.Trim()))
            {
                request.ConnectionString = Microsoft.SharePoint.SPContext.Current.Site.Url.ToString();
            }
            ClientContext clientCtx = new ClientContext(request.ConnectionString);
            Microsoft.SharePoint.Client.Web myweb = clientCtx.Web;
            Microsoft.SharePoint.Client.Web tempweb; ;
            clientCtx.Load(myweb, lists => lists.Lists.Where(list => list.BaseType == BaseType.GenericList && list.Hidden == false));
            clientCtx.ExecuteQuery();
            foreach (Microsoft.SharePoint.Client.List itemlist in myweb.Lists)
            {
                ClientContext clientCtx2 = new ClientContext(request.ConnectionString);
                ViewSchema vs = new ViewSchema();
                string listitem = itemlist.Title;
                vs.Name = itemlist.Title;
                vs.Description = itemlist.Description;
                tempweb = clientCtx2.Web;
                clientCtx2.Load(tempweb, lists => lists.Lists.Where(list => list.Title == listitem));
                clientCtx2.ExecuteQuery();
                List mylist = tempweb.Lists[0];
                clientCtx2.Load(mylist.Fields);
                clientCtx2.Load(mylist, p => p.Fields.Where(p2 => p2.Hidden == false && p2.FromBaseType == false));
                clientCtx2.ExecuteQuery();
                foreach (Field fld in mylist.Fields)
                {
                    Column tempcol = new Column();
                    tempcol.Name = fld.Title;
                    tempcol.Description = fld.Description;
                    tempcol.Type = GetDataType(fld.FieldTypeKind);
                    vs.Columns.Add(tempcol);
                }
                xresult.Add(vs);
                clientCtx2.Dispose();
            }
            clientCtx.Dispose();
            return xresult;
        }



        public override MapEntities.Shape GetShape(object data, ShapeItemBindingRule rule)
        {
            return null;
        }
    }
}
